//
//  UITextView+Addition.swift
//  SnowTrackTrainingScript
//
//  Created by iOS-Czz on 2023/11/33.
//

import Foundation
import UIKit

extension UITextView {
    
    func addPlaceholder(_ placeholder: String, color: UIColor = .lightGray) {
        let placeholderLabel = UILabel()
        placeholderLabel.text = placeholder
        placeholderLabel.font = self.font
        placeholderLabel.textColor = color
        placeholderLabel.sizeToFit()
        placeholderLabel.tag = 100
        placeholderLabel.isHidden = !self.text.isEmpty
        placeholderLabel.center = CGPoint(x: self.textContainerInset.left + placeholderLabel.bounds.width/2 + 5, y: self.textContainerInset.top + placeholderLabel.bounds.height/2)
        self.addSubview(placeholderLabel)
        self.delegate = self
    }
    
}

extension UITextView: UITextViewDelegate {
    
    public func textViewDidChange(_ textView: UITextView) {
        if let placeholderLabel = textView.viewWithTag(100) as? UILabel {
            placeholderLabel.isHidden = !textView.text.isEmpty
        }
    }
    
//    public func textViewDidBeginEditing(_ textView: UITextView) {
//        if let placeholderLabel = textView.viewWithTag(100) as? UILabel {
//            placeholderLabel.isHidden = true
//        }
//    }
    
    public func textViewDidEndEditing(_ textView: UITextView) {
        if let placeholderLabel = textView.viewWithTag(100) as? UILabel {
            placeholderLabel.isHidden = !textView.text.isEmpty
        }
    }
    
}



